package com.doordu.soa.service.web.utils;

import com.doordu.soa.service.web.fieldvalidator.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class ResponseUtil {
	/**
	 * 把数据写到jsp页面上
	 * 
	 * @Title: write
	 * @Description:
	 * @author xiaoqun.yi yixq@doordu.com
	 * @date 2017年3月22日 下午5:47:53
	 * @param response
	 * @param o
	 * @throws Exception
	 * @return void
	 */
	public static void write(HttpServletResponse response, Object o) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(o.toString());
		out.flush();
		out.close();
	}

	/**
	 * 把数据写入到excel
	 * 
	 * @Title: export
	 * @Description:
	 * @author xiaoqun.yi yixq@doordu.com
	 * @date 2017年3月22日 下午5:48:01
	 * @param response
	 * @param wb
	 * @param fileName
	 * @throws Exception
	 * @return void
	 */
	public static void export(HttpServletResponse response, Workbook wb, String fileName) throws Exception {
		// 固定格式
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
		OutputStream out = response.getOutputStream();// 输出流
		wb.write(out);
		out.flush();
		out.close();
	}
	
	public static void exportRoomTemplate(HttpServletResponse response, String path, String fileName) throws Exception {
		//以流的形式读取数据
		InputStream inp=ExcelUtil.class.getResourceAsStream(path);
		//poi文件流
		POIFSFileSystem fs=new POIFSFileSystem(inp);
		Workbook wb=new HSSFWorkbook(fs);
		// 固定格式
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
		OutputStream out = response.getOutputStream();// 输出流
		wb.write(out);
		out.flush();
		out.close();
	}
}
